Optional chaining operator in Javascript


Published on: January 29, 2021 By T.Andrew Rayan

Optional chaining operator allows us to access the nested properties of an object without caring about the existence of the properties in the object.

The optional chaining operators are used to handle the non-existing property problem of an object. The optional chaining operator is denoted by ?. operator.

Example

Output

undefined
Uncaught TypeError: Cannot read property 'streetName' of undefined

In the above example, we have an object, details with a property name. Now when trying to access a property address in the details which is not defined will log undefined. When trying to access the nested property streetName from address property, which is not defined will throw an error "Uncaught TypeError: Cannot read property 'streetName' of undefined".

In order to handle this scenario we can use optional chaining operator(?.).

Now, lets rewrite the above code with optional chaining operator.

Output

undefined
undefined

The variable before the ?. must be declared, else it will throw error.

We can also check whether the function exist or not using ?.() syntax.

Example

Output

User is admin
undefined

In the above example, user.admin?.() will check whether the admin function exist in the user object. If so will execute it else will return undefined.

user.master?.() will return undefined since master function does not exist.

There is an other syntax ?.[] , when we like to use brackets [] to access properties instead of dot notation.

Example

Output

Andrew
undefined

We can also remove the property of the object using ?. operator.

delete user?.firstName;

This will delete the firstName property from the object user if it exist else it will not throw any error.


Most Read